<template>
  <div class="custom-table-header">
    <el-table-column
      v-bind="columnProps"
      :label="label"
      :prop="prop"
      :width="width"
      :align="align"
    >
      <template #header>
        <div class="header-container" @click="handleHeaderClick">
          {{ label }}
          <el-popover
            v-model:visible="showPopover"
            placement="bottom"
            width="200"
            trigger="manual"
          >
            <div class="filter-options">
              <el-select
                v-model="selectedOption"
                placeholder="请选择"
                @change="handleFilterChange"
              >
                <el-option
                  v-for="option in filterOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <div class="filter-actions">
                <el-button
                  size="small"
                  type="primary"
                  @click="applyFilter"
                >
                  确定
                </el-button>
                <el-button
                  size="small"
                  @click="resetFilter"
                >
                  重置
                </el-button>
              </div>
            </div>
          </el-popover>
          <i class="el-icon-arrow-down" />
        </div>
      </template>
      <template #default="scope">
        <slot :row="scope.row" :$index="scope.$index"></slot>
      </template>
    </el-table-column>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const props = defineProps({
  label: {
    type: String,
    required: true,
  },
  prop: {
    type: String,
    required: true,
  },
  width: {
    type: [String, Number],
    default: 'auto',
  },
  align: {
    type: String,
    default: 'left',
  },
  filterOptions: {
    type: Array,
    default: () => [],
  },
  columnProps: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['filter-change']);

const showPopover = ref(false);
const selectedOption = ref(null);

const handleHeaderClick = () => {
  showPopover.value = !showPopover.value;
};

const handleFilterChange = (value) => {
  selectedOption.value = value;
};

const applyFilter = () => {
  emit('filter-change', selectedOption.value, props.prop);
  showPopover.value = false;
};

const resetFilter = () => {
  selectedOption.value = null;
  emit('filter-change', null, props.prop);
  showPopover.value = false;
};

watch(selectedOption, (newValue) => {
  if (newValue === null) {
    resetFilter();
  }
});
</script>

<style scoped>
.header-container {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.header-container i {
  margin-left: 5px;
  font-size: 12px;
}

.filter-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.filter-actions {
  display: flex;
  justify-content: space-between;
}
</style>